package bfa.cps;

import java.io.IOException;


import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;


public class BackgroundAudioService extends Service implements OnCompletionListener,OnPreparedListener,OnBufferingUpdateListener {

	private Handler handler=null;
	Bundle b = new Bundle();
	
	
	PhoneStateListener phoneStateListener=null;
	
	
	private SongListChecker songListChecker=null;
	
	private MediaPlayer player;
	
	private enum PlayerState {STOP, PAUSED, PLAYING};
	PlayerState playerState=PlayerState.STOP;
	
	
	private String actualRadioLocation;
	
	
	public void onCompletion(MediaPlayer mp) {
		stopPlaying();
	}
	
	@Override
	public void onCreate() {
		Log.i("LocalService", "Created");
		Toast.makeText(this, "My Background Created", Toast.LENGTH_LONG).show();

		actualRadioLocation=getString(R.string.defaultRadioLocation);
		
		initializeMediaPlayer();
		
		
		
		
		
		
		
		phoneStateListener = new PhoneStateListener() {
		    @Override
		    public void onCallStateChanged(int state, String incomingNumber) {
		        if (state == TelephonyManager.CALL_STATE_RINGING) {
		            //Incoming call: Pause music
		        	if (getPlayer()!=null) {
		        		if (getPlayer().isPlaying()) {
		        			getPlayer().pause();
		        			playerState=PlayerState.PAUSED;
		        			mandaMessaggio("TelephonyManager", "CALL_STATE_RINGING");
		        		}
		        	}
		        } else if(state == TelephonyManager.CALL_STATE_IDLE) {
		            //Not in call: Play music
		        	if (playerState==PlayerState.PAUSED) {
		        		if (getPlayer()!=null) {		        			
		        			getPlayer().start();
		        			playerState=PlayerState.PLAYING;
		        			mandaMessaggio("TelephonyManager", "CALL_STATE_IDLE");
		        		}
		        	}
		        } else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
		            //A call is dialing, active or on hold
		        	if (getPlayer()!=null) {
		        		if (getPlayer().isPlaying()) {
		        			getPlayer().pause();
		        			playerState=PlayerState.PAUSED;
		        			mandaMessaggio("TelephonyManager", "CALL_STATE_OFFHOOK");
	        			}
		        	}		        	
		        }
		        super.onCallStateChanged(state, incomingNumber);
		    }
		};

		
		
		
	}
//	@Override
//    public int onStartCommand(Intent intent, int flags, int startId) {
//        Log.i("LocalService", "Received start id " + startId + ": " + intent);
//        
//        startPlaying();
//        // We want this service to continue running until it is explicitly
//        // stopped, so return sticky.
//        return START_STICKY;
//    }

	
	@Override
	public void onStart(Intent intent, int startid) {
		//Toast.makeText(this, "My Background Started", Toast.LENGTH_LONG).show();
		if (songListChecker==null) {
			//Toast.makeText(this, "New checker", Toast.LENGTH_LONG).show();
			
			songListChecker=new SongListChecker();
			songListChecker.setRadioLocation(getActualRadioLocation());
			new Thread(songListChecker).start();
		}
	}
	
	
	@Override
	public IBinder onBind(Intent intent) {
		return new LocalBinder<BackgroundAudioService>(this);
		//return null;
	}

	private void initializeMediaPlayer() {
		playerState=PlayerState.STOP;
		
		setPlayer(new MediaPlayer());
        getPlayer().setOnPreparedListener(this);
        getPlayer().setOnBufferingUpdateListener(this);

        try {
            getPlayer().setDataSource(getActualRadioLocation());
            
            //sourceTextView.setText(HomeActivity.RADIO_STATION_URL);
            
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
	
	 public void startPlaying() {
		 	if (getPlayer()==null) {
		 		initializeMediaPlayer();
		 	}
		 
		 	try {
		 		getPlayer().prepareAsync();
		 	} catch (IllegalStateException e) {
		 		Log.e("IllegalStateException ", "" + e);	
		 		stopPlaying();
		 	}
	        
	        
	        
	        //String canz=Harvester.doIt(HomeActivity.RADIO_STATION_URL);
	        //songInfoTextView.setText(canz);
	    }
	 
	 @Override
	    public void onDestroy() {
	        // Cancel the persistent notification.
	        //mNM.cancel(NOTIFICATION);

	        // Tell the user we stopped.
	        //Toast.makeText(this, R.string.local_service_stopped, Toast.LENGTH_SHORT).show();
		 
		 	stopPlaying();
	    }


	 	public void stopPlaying() {
	 		if (getPlayer()!=null) {
		        if (getPlayer().isPlaying()) {
		            getPlayer().stop();
		            getPlayer().release();
		            //initializeMediaPlayer();
		        }	 			
	            setPlayer(null);
	            
	 		}
	 		
	 		playerState=PlayerState.STOP;
	 		
	 		
	 		TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
	 		if(mgr != null) {
	 		    mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
	 		}

	 		
	    }

		@Override
		public void onPrepared(MediaPlayer mp) {
        	mandaMessaggio("player","onPrepared");        	

        	
    		TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    		if(mgr != null) {
    		    mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
    		}
        	
    		if (getPlayer()!=null) {
            	getPlayer().start();
            	playerState=PlayerState.PLAYING;
    		}        	
		}

	    

		private void mandaMessaggio(String key,String valore) {
			if (getHandler()!=null) {	
			    Message msg = getHandler().obtainMessage();
			    b.putString(key,valore);
			    msg.setData(b);
			    getHandler().sendMessage(msg);
			 }
		}

		@Override
		public void onBufferingUpdate(MediaPlayer mp, int percent) {
            //Log.i("Duration", "" + mp.getDuration());
            //Log.i("Pos", "" + mp.getCurrentPosition());
            
            //Log.i("Buffering", "" + percent);
		}

		
		public boolean isPlaying()  {
			if (getPlayer()!=null) {
				return getPlayer().isPlaying();
			}
			
			return false;
		}

		public Handler getHandler() {
			return handler;
		}

		public void setHandler(Handler handler) {
			this.handler = handler;
			if (songListChecker!=null) {
				songListChecker.handler=handler;				
			}
		}

		public String getNewSong() {
			if (songListChecker!=null) {
				return songListChecker.getNewSong();
			}
			return "";
		}

		public String getNewTitle() {
			if (songListChecker!=null) {
				return songListChecker.getNewTitle();
			}
			return "";
		}

		/**
		 * @return the actualRadioLocation
		 */
		public String getActualRadioLocation() {
			return actualRadioLocation;
		}

		/**
		 * @param actualRadioLocation the actualRadioLocation to set
		 */
		public void setActualRadioLocation(String actualRadioLocation) {
			boolean different=(! this.actualRadioLocation.equals(actualRadioLocation));
			this.actualRadioLocation = actualRadioLocation;

			if (songListChecker!=null) {
				songListChecker.setRadioLocation(getActualRadioLocation());
				songListChecker.setMarci(getString(R.string.defaultMarci));
				
			}
			
			if (different) {
				initializeMediaPlayer();
			}
		}

		/**
		 * @return the player
		 */
		public MediaPlayer getPlayer() {
			return player;
		}

		/**
		 * @param player the player to set
		 */
		public void setPlayer(MediaPlayer player) {
			this.player = player;
		}

		public void stopAll() {
			disableSongListCheker();
			if (songListChecker!=null) {
				songListChecker.keepOn=false;				
			}
			
			stopSelf();
			
		}
		public void disableSongListCheker() {
			if (songListChecker!=null) {
				songListChecker.setPermitWork(false);
			}
		}
		public void enableSongListCheker() {
			if (songListChecker!=null) {
				songListChecker.setPermitWork(true);
			}
		}
		
}
